/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler.action;

import com.funcom.peeler.peelable.PeelComponent;
import com.funcom.peeler.peelable.PeelContainer;
import java.awt.*;

public class Move implements Change {

    int start_x, end_x, start_y, end_y;
    PeelComponent component;
    PeelContainer start_parent, end_parent;

    public Move( PeelComponent component ) {
         if ( component == null ) throw new NullPointerException( "Move must act on a valid component" );
         this.component = component;
    }

    public Move( PeelComponent component, Point old_pos, Point new_pos ) {
        if ( component == null || old_pos == null || new_pos == null ) throw new NullPointerException( "Move must be created with valid parameters" );
        this.component = component;
        this.start_x = old_pos.x;
        this.start_y = old_pos.y;
        this.end_x = new_pos.x;
        this.end_y = new_pos.y;
        this.start_parent = component.getParent();
        this.end_parent = component.getParent();
    }

    public void doChange() {
        component.getComponent().setLocation( end_x, end_y );
        reparent( end_parent );
    }

    public void undoChange() {
        component.getComponent().setLocation( start_x, start_y );
        reparent( start_parent );
    }

    public void startChange() {
        start_x = component.getComponent().getX();
        start_y = component.getComponent().getY();
        start_parent = component.getParent();
    }

    public void endChange() {
        end_x = component.getComponent().getX();
        end_y = component.getComponent().getY();
        end_parent = component.getParent();
    }

    private void reparent( PeelContainer container ) {
        if ( container == null ) return;
        if ( start_parent == end_parent ) return;
        component.detach();
        container.addChild( component );
    }

    public boolean valid() {

        if ( ( start_parent == end_parent ) && ( start_x == end_x ) && ( start_y == end_y ) ) return false;

        return true;
    }
}

